<?php
namespace app\admin\controller;
use think\Controller;

class Type extends Controller
{
	private  $obj;
    public function _initialize() {
        $this->obj = model("Type");
    }

	public function index()
	{
		$parentId = input('get.parent_id', 0, 'intval');
		$types = $this->obj->getFirstTypes($parentId);
		return $this->fetch('',[
			'types' => $types,
		]);
	}
	/**
	 * 添加分类页面
	 */
	public function add()
	{
		$types = $this->obj->getNormalFirstType();
		return $this->fetch('',[
			'types' => $types,
		]);
	}
	/**
	 * 保存分类
	 * @return [type] [description]
	 */
	public function save()
	{
		if (!request()->isPost()) {
			$this->error('请求失败');
		}
		$data = input('post.');

		if (!empty($data['id'])) {
			return $this->update($data);
		}

		$validate = validate('Type');
		if (!$validate->scene('add')->check($data)) {
			$this->error($validate->getError());
		}

		$res = $this->obj->add($data);
		if ($res) {
			$this->success('添加成功');
		} else {
			$this->error('添加失败');
		}
	}

	/**
	 * 编辑
	 * @param  integer $id [description]
	 * @return [type]      [description]
	 */
	public function edit($id=0)
	{
		if (intval($id) < 1) {
			$this->error('参数不合法');
		}
		$typeinfo = $this->obj->get($id);
		$types = $this->obj->getNormalFirstType();
		return $this->fetch('',[
			'typeinfo' => $typeinfo,
			'types' => $types,
		]);
	}

	public function update($data)
	{
		$res = $this->obj->save($data,['id'=>intval($data['id'])]);
		if ($res) {
			$this->success('编辑成功');
		} else{
			$this->error('编辑失败');
		}
	}

	// 排序功能
	public function listorder($id,$listorder)
	{
		$res = $this->obj->save(['listorder'=>$listorder],['id'=>$id]);
		if ($res) {
			$this->result($_SERVER['HTTP_REFERER'], 1, 'success');
		} else {
			$this->result($_SERVER['HTTP_REFERER'], 0, '更新失败');
		}
	}

	// 状态
	public function status()
	{
		if (!request()->isGet()) {
			$this->error('请求不合法');
		}
		$data = input('get.');
		$validate = validate('Type');
		if (!$validate->scene('status')->check($data)) {
			$this->error($validate->getError());
		}
		$res = $this->obj->save(['status'=>$data['status']],['id'=>$data['id']]);
		if ($res) {
			$this->success('状态更改成功');
		} else {
			$this->error('状态更改失败');
		}
	}

	// 获取二级分类目录
	public function getSecondType()
	{
		$id = input('post.id');
		if (!$id) {
			$this->error('ID不合法');
		}
		// 通过一级ID获取二级目录
		$secType = $this->obj->getFirstTypes($id);
		if (!$secType) {
			return show(0,'error');
		}
		return show(1,'success',$secType);
	}
}